package com.jky.trial.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jky.trial.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;


public class JWTUtil {

    private static final Logger log = LoggerFactory.getLogger(JWTUtil.class);

    // 过期时间30天
    private static final long EXPIRE_TIME = 60 * 60 * 1000*24*30;

    /**
     * 生成签名,30天后过期
     *
     * @param user 用户
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(User user, String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带username信息
        return JWT.create()
                .withClaim("name", user.getName())
                .withClaim("username", user.getUserName())
                .withClaim("id", user.getId().toString())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token,
                                 String name,
                                 String username,
                                 String id,
                                 String secret)  {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm)
                .withClaim("name", name)
                .withClaim("username", username)
                .withClaim("id", id)
                .build();
        try {
            DecodedJWT jwt = verifier.verify(token);
        }catch (Exception e){
//            httpServletResponse.
//            HttpServletResponse httpServletResponse = (HttpServletResponse) resp;
//            httpServletResponse.sendRedirect("/401");
        }

        return true;
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("username").asString();
    }
    public static String getName(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("name").asString();
    }
    public static String getId(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("id").asString();
    }
    public static User getUser(String token) {
        DecodedJWT jwt = JWT.decode(token);
        User user = new User();
        user.setId(Integer.valueOf(jwt.getClaim("id").asString()));

        user.setName(jwt.getClaim("name").asString());
        user.setUserName(jwt.getClaim("username").asString());
        return user;
    }

}

